package com.cf.mvp.base;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleRegistry;

import com.cf.mvp.mvp.IBaseView;
import com.cf.mvp.mvp.IPresenter;
import com.cf.mvp.mvp.proxy.ProxyImpl;
import com.cf.mvp.rx.LifecycleToRxSubject;
import io.reactivex.subjects.BehaviorSubject;


/**
 * @author yangji
 */
public class BaseFragment<P extends IPresenter> extends Fragment implements IBaseView {

    private LifecycleToRxSubject subject = LifecycleToRxSubject.create();

    /**
     * 重写 Fragment 生命周期
     */
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    @Override
    public BehaviorSubject<Lifecycle.Event> getSubject() {
        return subject.getSubject();
    }

    private ProxyImpl<P> proxyPresenter;

    public P getPresenter() {
        return proxyPresenter.getMainPresenter();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        proxyPresenter = new ProxyImpl<P>() {
        };
        proxyPresenter.bindPresenter(this);
        getLifecycle().addObserver(subject);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (proxyPresenter != null) {
            proxyPresenter.unBindPresenter();
        }
    }
}
